package org.fjsei.yewu.service.third;
import lombok.Data;
import lombok.experimental.Accessors;
import lombok.extern.slf4j.Slf4j;
import md.specialEqp.Eqp;
import org.fjsei.yewu.entity.fjtj.PipeLineUnit;
import org.fjsei.yewu.exception.CommonGraphQLException;
import org.fjsei.yewu.pojo.SliceSyncRes;
import org.fjsei.yewu.resolver.MaintComn;
import org.jgroups.util.Triple;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

//  https://blog.csdn.net/zhangbeizhen18/article/details/125939665
//连接到第三方平台的REST 客户端接口；在后端发起的三方调用等待收集结果。 RestTemplate  https://blog.csdn.net/D1842501760/article/details/124216538
//被org.springframework.web.reactive.client.WebClient所reactive版WebFlux?   https://www.jdon.com/55606.html
@Data
@Accessors(chain = true)
class LoginResponseData {
    private Boolean pwd_expired;
    private String access_token;
    private String brief_token;
}
@Data
@Accessors(chain = true)
class LoginResponse {
    private int code;
    private String msg;
    private LoginResponseData data;
}

/*
对接旧检验平台的：
* */
@Slf4j
@Service
public class MyRestServiceClient {
    private final RestTemplate restTemplate;
    private final CookieManagingService cookieManagingService;
    @Deprecated
    @Value("${sei.Jyinf.token:}")
    private String jyToken;         //淘汰了！
    //Admin-Expires-In= 后面的部分 ; @直接附加更多的Key=Value ;
    @Value("${sei.Jyinf.cookie:}")
    private String jyCookie;
    @Value("${sei.Jyinf.endpoint:}")
    private String jyEndpoint;
    @Value("${sei.Jyinf.username:}")
    private String username;
    @Value("${sei.Jyinf.password:}")
    private String password;
    @Value("${sei.Jyinf.uuid:}")
    private String uuidLogin;

    private static final Logger LOGGER = LoggerFactory.getLogger(MyRestServiceClient.class);

    public MyRestServiceClient(RestTemplateBuilder restTemplateBuilder, CookieManagingService cookieManagingService) {
        this.restTemplate = restTemplateBuilder.build();
        this.cookieManagingService = cookieManagingService;
    }
    // 提供一个方法来登录并保存cookie
    public Boolean refreshLogin() {
        OldLoginBody sendb=new OldLoginBody();
        sendb.setUsername(username).setUserType(10L).setPassword(password).setUuid(uuidLogin);
        ResponseEntity<LoginResponse> responseEntity = cookieManagingService.getRestTemplate()
                .postForEntity(jyEndpoint + "prod-api/auth/login", sendb, LoginResponse.class);
        LoginResponse resp = responseEntity.getBody();
        if(200==resp.getCode() && resp.getData()!=null) {
            String token=resp.getData().getAccess_token();
            cookieManagingService.putExpiresToken(jyCookie,token);
            log.info("jy Inf刷新了:token={}", token);
            return true;
        }
        return false;
    }
    public <T> InfRespond<T> postFor(String urlT, HttpMethod method, ParameterizedTypeReference<InfRespond<T>> typeRef, @Nullable HttpEntity<?> requestEntity) {
        ResponseEntity<InfRespond<T>> responseEntity = cookieManagingService.getRestTemplate().exchange(jyEndpoint + urlT, method, requestEntity, typeRef);
        InfRespond<T> resp = responseEntity.getBody();
        int code = resp.getCode();     //resp.getMsg();
        if(code==401) {
            if(!refreshLogin())  throw new CommonGraphQLException("无法联机Inf",urlT);
            responseEntity = cookieManagingService.getRestTemplate().exchange(jyEndpoint + urlT, method, requestEntity, typeRef);
            resp = responseEntity.getBody();
        }
        return resp;
    }
    //面对特别异常：不用停止的
    public <T>  DataRespond<T> throwInfException(Exception e) {
        e.printStackTrace();
        String trun = e.getMessage().length() > 250 ? e.getMessage().substring(0, 250) : e.getMessage();
        //规定的报错信息：不要抛给上一级了！目的=避免任务被暂停！
        if("500 Internal Server Error: \"{\"msg\":\"未知异常，请联系运维人员！\",\"code\":500}\"".equals(trun)) {
            DataRespond<T> err =new DataRespond<>();
            err.setMsg(trun);
            err.setCode(500);
            return err;
        }
        throw new CommonGraphQLException(e.getMessage(),"inf");
    }
    public <T> DataRespond<T> postForD(String urlT, HttpMethod method, ParameterizedTypeReference<DataRespond<T>> typeRef, @Nullable HttpEntity<?> requestEntity) {
        //log.info("postForD: urlT{}", urlT);  500 Internal Server Error: "{"msg":"未知异常，请联系运维人员！","code":500}"
        ResponseEntity<DataRespond<T>> responseEntity =null;
        try {
            responseEntity = cookieManagingService.getRestTemplate().exchange(jyEndpoint + urlT, method, requestEntity, typeRef);
        } catch (Exception e) {
            return throwInfException(e);
        }
        //        log.info("postForD: 回答{}", responseEntity.toString());
        DataRespond<T> resp = responseEntity.getBody();
        int code = resp.getCode();     //resp.getMsg();
        if(code==401) {
            if(!refreshLogin())  throw new CommonGraphQLException("无法联机Inf",urlT);
            try {
                responseEntity = cookieManagingService.getRestTemplate().exchange(jyEndpoint + urlT, method, requestEntity, typeRef);
            } catch (Exception e) {
               return throwInfException(e);
            }
            resp = responseEntity.getBody();
        }
        return resp;
    }
    //仅当演示
    public List<Eqp> getBooks() {
        ResponseEntity<Eqp[]> responseEntity = restTemplate.getForEntity(
                "http://localhost:3000/Books",
                Eqp[].class
        );
        return Arrays.asList(responseEntity.getBody());
    }
    //仅当演示
    public List<Eqp> getAuthorBooks(String authorId) {
        ResponseEntity<Eqp[]> responseEntity = restTemplate.getForEntity(
                "http://localhost:3000/Books",
                Eqp[].class
        );
        List<Eqp> Books = Arrays.asList(responseEntity.getBody());

        return Books.stream().filter(Book -> Book.getId().equals(authorId)).collect(Collectors.toList());
    }
    public List<Eqp> getDeviceNos2() {
        ResponseEntity<Eqp[]> responseEntity = restTemplate.getForEntity(
                "https://36.212.134.165:10443/prod-api/busimge/eqp/selectList?pageNum=1&eqpIspDepts=&eqpUseStas=2,3&seipEqpType=100&pageSize=50&curMenuId=100019&curMenuName=法定设备台账&time=1736207283162",
                Eqp[].class
        );
        return Arrays.asList(responseEntity.getBody());
    }
    //仅当演示
    public Eqp getAuthor(String AuthorId) {
        ResponseEntity<Eqp> responseEntity = restTemplate
                .getForEntity("http://localhost:3000/Authors/{AuthorId}", Eqp.class, AuthorId);
        return responseEntity.getBody();
    }
    public InfRespond get地区区域() {
        cookieManagingService.putExpiresToken(jyCookie,jyToken);
        ParameterizedTypeReference<InfRespond<AreaCodName>> typeRef = new ParameterizedTypeReference<InfRespond<AreaCodName>>() {};
        ResponseEntity<InfRespond<AreaCodName>> responseEntity = cookieManagingService.getRestTemplate().exchange(
                jyEndpoint +"prod-api/busimge/dict/areacod/list?curMenuId=100013",
                HttpMethod.GET, null, typeRef
        );
        return responseEntity.getBody();
    }
    public InfRespond get楼盘名() {
        cookieManagingService.putExpiresToken(jyCookie,jyToken);
        ParameterizedTypeReference<InfRespond<HouseBuilding>> typeRef = new ParameterizedTypeReference<InfRespond<HouseBuilding>>() {};
        ResponseEntity<InfRespond<HouseBuilding>> responseEntity = cookieManagingService.getRestTemplate().exchange(
                jyEndpoint +"prod-api/busimge/housemge/list?pageNum=1&pageSize=299999",
                HttpMethod.GET, null, typeRef
        );
        return responseEntity.getBody();
    }
    public InfRespond get单位表(int page,int pagesize) {
        cookieManagingService.putExpiresToken(jyCookie,jyToken);
        ParameterizedTypeReference<InfRespond<OldPtUnit>> typeRef = new ParameterizedTypeReference<>() {};
        ResponseEntity<InfRespond<OldPtUnit>> responseEntity = cookieManagingService.getRestTemplate().exchange(
                jyEndpoint +"prod-api/busimge/untmge/list?pageNum="+page+"&pageSize="+pagesize,
                HttpMethod.GET, null, typeRef
        );
        return responseEntity.getBody();
    }
    public InfRespond get使用单位部门(Long untid) {
        cookieManagingService.putExpiresToken(jyCookie,jyToken);
        ParameterizedTypeReference<InfRespond<OldDepartment>> typeRef = new ParameterizedTypeReference<>() {};
        ResponseEntity<InfRespond<OldDepartment>> responseEntity = cookieManagingService.getRestTemplate().exchange(
                jyEndpoint +"prod-api/busimge/untDept/list?untId="+untid,
                HttpMethod.GET, null, typeRef
        );
        return responseEntity.getBody();
    }
    public InfRespond<OldSecudept> get使用单位机构分支(Long untid) {
        ParameterizedTypeReference<InfRespond<OldSecudept>> typeRef = new ParameterizedTypeReference<>() {};
        return postFor("prod-api/busimge/untSecudept/list?untId=" + untid, HttpMethod.GET, typeRef, null);
    }
    public InfRespond<JianyanDepOffice> get检验机构部门科室(String tjyname) {
        ParameterizedTypeReference<InfRespond<JianyanDepOffice>> typeRef = new ParameterizedTypeReference<>() {};
        return postFor("prod-api/system/dept/treeselect?curMenuId=10001339", HttpMethod.GET, typeRef, null);
    }
    public InfRespond<EqpCodOidno> getDeviceNos(int page,int pagesize) {
        ParameterizedTypeReference<InfRespond<EqpCodOidno>> typeRef = new ParameterizedTypeReference<>() {};
        return postFor("prod-api/busimge/eqp/selectList?pageNum="+page+"&pageSize="+pagesize+"&curMenuId=100019", HttpMethod.GET, typeRef, null);
    }
    public  DataRespond<OldDeviceSkel<ElvPara>> getDeviceParamElv(Long eqpid) {
        ParameterizedTypeReference<DataRespond<OldDeviceSkel<ElvPara>>> typeRef = new ParameterizedTypeReference<>() {};
        return postForD("prod-api/busimge/eqp/"+eqpid, HttpMethod.GET, typeRef, null);
    }
    public  DataRespond<OldDeviceSkel<VesPara>> getDeviceParamVes(Long eqpid) {
        ParameterizedTypeReference<DataRespond<OldDeviceSkel<VesPara>>> typeRef = new ParameterizedTypeReference<>() {};
        return postForD("prod-api/busimge/eqp/"+eqpid, HttpMethod.GET, typeRef, null);
    }
    public  DataRespond<OldDeviceSkel<NpvsPara>> getDeviceParamNpvs(Long eqpid) {
        ParameterizedTypeReference<DataRespond<OldDeviceSkel<NpvsPara>>> typeRef = new ParameterizedTypeReference<>() {};
        return postForD("prod-api/busimge/eqp/"+eqpid, HttpMethod.GET, typeRef, null);
    }
    public  DataRespond<OldDeviceSkel<LiftPara>> getDeviceParamLift(Long eqpid) {
        ParameterizedTypeReference<DataRespond<OldDeviceSkel<LiftPara>>> typeRef = new ParameterizedTypeReference<>() {};
        return postForD("prod-api/busimge/eqp/"+eqpid, HttpMethod.GET, typeRef, null);
    }
    public  DataRespond<OldDeviceSkel<CraPara>> getDeviceParamCra(Long eqpid) {
        ParameterizedTypeReference<DataRespond<OldDeviceSkel<CraPara>>> typeRef = new ParameterizedTypeReference<>() {};
        return postForD("prod-api/busimge/eqp/"+eqpid, HttpMethod.GET, typeRef, null);
    }
    public  DataRespond<OldDeviceSkel<BoilPara>> getDeviceParamBoil(Long eqpid) {
        ParameterizedTypeReference<DataRespond<OldDeviceSkel<BoilPara>>> typeRef = new ParameterizedTypeReference<>() {};
        return postForD("prod-api/busimge/eqp/"+eqpid, HttpMethod.GET, typeRef, null);
    }
    public  DataRespond<OldDeviceSkel<CarPara>> getDeviceParamCar(Long eqpid) {
        ParameterizedTypeReference<DataRespond<OldDeviceSkel<CarPara>>> typeRef = new ParameterizedTypeReference<>() {};
        return postForD("prod-api/busimge/eqp/"+eqpid, HttpMethod.GET, typeRef, null);
    }
    public  DataRespond<OldDeviceSkel<AmusPara>> getDeviceParamAmus(Long eqpid) {
        ParameterizedTypeReference<DataRespond<OldDeviceSkel<AmusPara>>> typeRef = new ParameterizedTypeReference<>() {};
        return postForD("prod-api/busimge/eqp/"+eqpid, HttpMethod.GET, typeRef, null);
    }
    public  DataRespond<OldDeviceSkel<PpinPara>> getDeviceParamPpin(Long eqpid) {
        ParameterizedTypeReference<DataRespond<OldDeviceSkel<PpinPara>>> typeRef = new ParameterizedTypeReference<>() {};
        return postForD("prod-api/busimge/eqp/"+eqpid, HttpMethod.GET, typeRef, null);
    }
    public InfRespond<PipeLineUnit> getPipelineParam(int page, int pagesize) {
        ParameterizedTypeReference<InfRespond<PipeLineUnit>> typeRef = new ParameterizedTypeReference<>() {};
        return postFor("prod-api/busimge/pipelineunit/list?pageNum="+page+"&pageSize="+pagesize, HttpMethod.GET, typeRef, null);
    }

}
